<template>
  <div class="avatar-container">
    <el-upload
      class="avatar-uploader"
      action="#"
      :auto-upload="false"
      :on-change="onAvaterChange"
      :show-file-list="false"
    >
      <img
        v-if="avatorInfo.imageUrl"
        :src="avatorInfo.imageUrl"
        class="avatar"
      />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <div class="item">
      <input
        class="input_dash"
        v-model="avatorInfo.name"
        @change="dataChange"
      />
    </div>
    <div class="item">
      <input class="input_dash" v-model="avatorInfo.job" @change="dataChange" />
    </div>
  </div>
</template>
<script>
import { nanoid } from 'nanoid'
export default {
  name: 'Avatar',
  data() {
    return {
      avatorInfo: {
        imageUrl: '',
        name: '庞巧玲',
        job: '前端开发工程师',
      },
      id: '',
    }
  },
  props: {
    avtarProps: {
      type: Object,
      default: function () {
        return {
          imageUrl: '/static/avatar-xx.png',
          name: 'lemon',
          job: '前端开发工程师',
        }
      },
    },
    moduleId: {
      type: String,
      default: nanoid(),
    },
  },
  created() {
    this.avatorInfo = { ...this.avtarProps }
    this.id = this.moduleId
  },
  methods: {
    // 信息改变
    dataChange() {
      this.updateStore()
    },
    // 同步更新仓库数据
    updateStore() {
      const newData = { props: this.avatorInfo, id: this.id }
      this.$store.commit('setModule', newData)
    },
    // 头像改变
    onAvaterChange(file, fileList) {
      var _this = this
      var event = event || window.event
      var file = event.target.files[0]
      var reader = new FileReader()
      // 将头像转base64
      reader.onload = function (e) {
        _this.avatorInfo.imageUrl = e.target.result //将图片路径赋值给src
        _this.updateStore()
      }
      reader.readAsDataURL(file)
    },
  },
}
</script>
<style lang="less" scoped>
.avatar-container {
  margin-bottom: 5px;
}
.avatar-uploader,
.el-upload {
  cursor: pointer;
  position: relative;
  margin-top:15px;
  overflow: hidden;
  text-align: center;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  margin-top: 3px;
  font-size: 28px;
  color: #8c939d;
  width: 2.5cm;
  height: 3.5cm;
  line-height: 3.5cm;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar {
  width: 2.5cm;
  height: 3.5cm;
  border-radius: 50% 50%;
  display: block;
}
.item {
  text-align: center;
  padding: 10px 5px;
}
.input_dash {
  height: 25px;
  width: 150px;
  text-align: center;
  border-color: white;
  border-width: 0ch;
  background-color: transparent;
  color: white;
  font-size: 20px;
}
.input_dash:focus {
  background: none;
  outline: none;
  border: 0px;
  //    padding: 5px;
  border-color: tomato;
  border-width: 1px;
  border-style: dotted;
}
</style>
